package com.m3958.firstgwt.client.datasource;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.JsArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.m3958.firstgwt.client.AppStatus;
import com.m3958.firstgwt.client.rpc.MyRpcCallback;
import com.m3958.firstgwt.client.types.SmartOperationName;
import com.m3958.firstgwt.client.types.SmartResponseFieldName;
import com.m3958.firstgwt.shared.type.CommonField;
import com.m3958.firstgwt.shared.type.SmartConstants;
import com.m3958.firstgwt.shared.type.SmartParameterName;
import com.m3958.gwtutil.clientside.client.jso.AssetJso;
import com.m3958.gwtutil.clientside.client.utils.JsoUtil;
import com.smartgwt.client.rpc.RPCManager;
import com.smartgwt.client.rpc.RPCRequest;
import com.smartgwt.client.rpc.RPCResponse;

@Singleton
public class AssetAsyncDataProvider extends AsyncDataProvider<AssetJso>{
	
	@Inject
	private AppStatus aservice;
	
	@Inject
	private JsoUtil jsoUtil;

	@Override
	protected void onRangeChanged(HasData<AssetJso> display) {
		Range range = display.getVisibleRange();
		fetchData(range);
	}

	private void fetchData(final Range range) {
		Map<String, String> m = new HashMap<String, String>();
    	m.put(SmartParameterName.MODEL_NAME, AssetDataSource.className);
    	m.put(SmartParameterName.OPERATION_TYPE, SmartOperationName.FETCH.getValue());
    	m.put(SmartParameterName.FETCH_OWNER, String.valueOf(true));
    	m.put(CommonField.SITE_ID.getValue(), aservice.getSiteId());
    	m.put(SmartParameterName.SORTBY, "-createdAt");
    	m.put(SmartParameterName.START_ROW, range.getStart()+"");
    	m.put(SmartParameterName.END_ROW, (range.getStart() + range.getLength()) + "");
    	RPCRequest rr = new RPCRequest();
    	rr.setHttpMethod("GET");
    	rr.setActionURL(SmartConstants.SMART_CRUD_URL);
    	rr.setParams(m);
    	RPCManager.sendRequest(rr,new MyRpcCallback(){
			@Override
			public void afterSuccess(RPCResponse response,JSONObject responseJo, RPCRequest request, JSONValue data) {
				int totalNum = new Double(responseJo.get(SmartResponseFieldName.TOTAL_ROWS).isNumber().doubleValue()).intValue();
				JsArray<AssetJso> aj = data.isArray().getJavaScriptObject().cast();
				updateRowCount(totalNum, true);
				updateRowData(range.getStart(), jsoUtil.convertToList(aj));
			}});
	}

}
